<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        v-model="ruleForm.password"
        type="password"
        autocomplete="off"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="loginFn(ruleFormRef)">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'
import { adminLoginAPI, getAdminUserInfoAPI } from '@/api'
import type { FormInstance } from 'element-plus'

// 获取当前的路由信息
const router = useRouter()
// 获取vuex
const store = useStore()

// 获取el-form对象
const ruleFormRef = ref<FormInstance>()

// 定义表单数据
const ruleForm = reactive({
  username: 'admin',
  password: '123456',
})

// 密码框自定义验证
const validatePwd = (rule: any, value: any, callback: any) => {
  // 这个value就是密码框的value
  if (!value) {
    // 验证不成功，抛出错误。
    callback(new Error('密码不能为空！'))
  } else {
    // 验证成功，直接调用callback。
    callback()
  }
}

// 检验规则
const rules = reactive({
  username: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
  password: [{ validator: validatePwd, trigger: 'blur' }],
})

// 点击登录按钮
const loginFn = (ruleFormRef: any) => {
  if (!ruleFormRef) return
  ruleFormRef.validate(async (valid: any) => {
    if (valid) {
      // 所有的都验证通过
      const res = await adminLoginAPI(ruleForm)
      if (res.code == 200) {
        // 1.存token， {expires: 7} -> 表示7天后过期
        Cookies.set('token', res.data.tokenHead + res.data.token, {
          expires: 7,
        })
        // 2.获取用户信息
        getAdminUserInfoAPI().then((res) => {
          if (res.code == 200) {
            // 3.将用户信息存储到vuex中
            // console.log(res.data)
            store.commit('updataMenus', res.data.menus)
            // 4.跳转到首页
            router.push('/home')
          } else {
            ElMessage.error('获取用户信息失败')
          }
        })
      }
    } else {
      ElMessage.error('登录失败')
      // 验证失败
      return false
    }
  })
}
</script>

<style scoped lang="scss"></style>
